package ddbs;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DatabaseQuery {
    static int port;
    static String host;
    static String username;
    static String passwd;
    static String dbname;
    static String url = null;
    static LinkedList<Connection> conns=null;

    public static void test() {
        Data d = query("SELECT * from book limit 5");
        d.generateHtmlTable();
    }

    public static boolean init(Configuration conf) {
        int port = Integer.parseInt(conf.getConf("DB_PORT"));
        String host = conf.getConf("DB_HOST");
        String dbname = conf.getConf("DB_NAME");
        String username = conf.getConf("DB_USER");
        String passwd = conf.getConf("DB_PASSWD");
        url = "jdbc:mysql://" + host + ":" + port + "/" + dbname + "?"
                + "user=" + username + "&password=" + passwd;
        conns = new LinkedList<Connection>();
        Connection c = getConnection();
        conns.add(c);
        // test();
        return true;
    }

    @SuppressWarnings("unused")
    private static Connection getConnection2() {
        Connection conn = null;
        try {
            InitialContext ctx = new InitialContext();
            DataSource ds = (DataSource) ctx
                    .lookup("java:comp/env/jdbc/MySQLDB");
            conn = ds.getConnection();
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return conn;
    }

    private static synchronized Connection getConnection() {
        if (conns.size() > 0)
            return conns.poll();
        Connection conn = null;
        try {
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            conn = DriverManager.getConnection(url);
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }
        return conn;
    }

    private static synchronized void putConnection(Connection conn) {
        conns.add(conn);
    }

    @SuppressWarnings("unused")
    private static void showResultSet(ResultSet rs) {
        ResultSetMetaData meta = null;
        try {
            meta = rs.getMetaData();
            int columns = meta.getColumnCount();
            System.out.println("columns = " + columns);
            for (int i = 1; i < columns; ++i) {
                System.out.print(meta.getColumnName(i) + "\t");
            }
            while (rs.next()) {
                for (int i = 1; i <= columns; ++i) {
                    Object obj = rs.getObject(i);
                    System.out.print(obj + "\t");
                }
                System.out.println();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static Data query(String sql) {
        //if (sql.indexOf("where") < 0)   sql = sql + " limit 5";

        Connection conn = getConnection();
        Statement stmt = null;
        ResultSet rs = null;
        Data d = null;
        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            d = new Data(rs);
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException sqlEx) {
                }
                rs = null;
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException sqlEx) {
                }
                stmt = null;
            }
            putConnection(conn);
        }
        //String msg = new String(d.serialize());
        //int length = msg.length();
        //if (length> 50) length =50;
        //System.out.println("Query database "+sql+" result :" + msg.substring(0, length));
        return d;
    }
}
